jsx3.require("ux.megatron.gui.Matrix");

jsx3.Class.defineClass("ux.cdb.admin.gui.Matrix", ux.megatron.gui.Matrix, null,
function(matrix) {
    matrix.EVENT_CHECKALL = "EVENT_MATRIX_CHECKALL";
    matrix.SELECT_TIMESPAN = 200;

    matrix.prototype.init = function(strName) {
        this.jsxsuper(strName);
    }

    matrix.prototype.checkAllRecords = function(objChkbox) {
        var iter = this.getXML().getChildNodes().iterator();
        while (iter.hasNext()) {
            iter.next().setAttribute('jsxchecked', objChkbox.checked ? 1: 0);
        };
        this.repaintData();
        this.publish({"subject":matrix.EVENT_CHECKALL,"checked":objChkbox.checked});
    }
    
    matrix.prototype.onSetParent = function(parent) {
        if(!jsx3.ide) {
            this.selectEvent = this.getEvent("jsxselect");
            this.removeEvent("jsxselect");
            this.subscribe("jsxselect", this, this.onSelectRecord);
        }
        return this.jsxsuper(parent);
    }
    
    matrix.prototype.onSelectRecord = function(objEvent) {
        if (objEvent.context.objCOLUMN.getPath() == "jsxchecked") {
            if(this.arrSelectedIds && this.arrSelectedIds.length != 0) {
                for(var i=0; i<this.arrSelectedIds.length; i++) {
                    this.selectRecord(this.arrSelectedIds[i]);
                }
            } else {
                this.deselectAllRecords();
            }
        } else {
            if(this.selectTime) {
                var interval = new Date().getTime() - this.selectTime;
            }
            this.selectTime = new Date().getTime();
            if(interval && interval<matrix.SELECT_TIMESPAN && this.lastCall){
                window.clearTimeout(this.lastCall);
            }
            var that = this;
            this.lastCall = window.setTimeout(function(){
                jsx3.eval.call(that, that.selectEvent, objEvent.context);
            },matrix.SELECT_TIMESPAN);
        }
        this.arrSelectedIds = this.getSelectedIds();
    }

    matrix.prototype.getCheckedNodes = function() {
        return this.getXML().selectNodes("//record[@jsxchecked=1]");
    }

    matrix.prototype.clear = function() {
        this.arrSelectedIds = null;
        this.cacheCDF = null;
    }
    
    matrix.prototype.filter = function(columnName, value) {
        this.cacheCDF = this.cacheCDF || this.getXML();
        var cdf = null;
        if(columnName && value) {
            if(this.get(columnName)) {
                cdf = jsx3.xml.CDF.Document.newDocument();
                var iter = this.cacheCDF.selectNodes("//record[contains(@"+this.get(columnName).getPath()+",'"+value+"')]").iterator();
                while(iter.hasNext()) {
                    cdf.appendChild(iter.next().cloneNode(true));
                }
            }
        } else {
            cdf = this.cacheCDF;
        }
        this.setSourceXML(cdf);
        this.repaintData();
    }

});